package com.hoshiicloud.vericenter.service.impl;

import com.hoshiicloud.vericenter.entity.vo.SendMsgWorkResponse;
import com.hoshiicloud.vericenter.result.Response;
import com.hoshiicloud.vericenter.service.SmsService;
import com.yunpian.sdk.YunpianClient;
import com.yunpian.sdk.model.Result;
import com.yunpian.sdk.model.SmsBatchSend;
import com.yunpian.sdk.model.SmsSingleSend;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class SmsServiceImpl implements SmsService {

    /**
     * 根据参数map组装字符串
     *
     * @param param
     * @return
     */
    private String getTplValueStr(Map<String, String> param) {
        String tplValue = "";
        String encoding = "UTF-8";
        for (Map.Entry<String, String> entry : param.entrySet()) {
            try {
                tplValue += URLEncoder.encode(("#" + entry.getKey() + "#"), encoding) + "=" + URLEncoder
                        .encode(entry.getValue(), encoding) + "&";
            } catch (UnsupportedEncodingException e) {
                throw new AssertionError("UTF-8 not supported");
            }
        }
        if (tplValue.length() > 0) {
            tplValue = tplValue.substring(0, tplValue.length() - 1);
        }
        return tplValue;
    }

    /**
     * 发送短信验证码
     *
     * @param mobile
     * @return
     */
    @Override
    public Response sendCode(String mobile, String code, String tplId, String apiKey) {
        YunpianClient client = new YunpianClient(apiKey).init();
        //String code= String.valueOf ((int)((Math.random()*9+1)*100000));
        Map<String, String> tplValueMap = new HashMap<>();
        tplValueMap.put("code", code);
        String tplValue = getTplValueStr(tplValueMap);
        Map<String, String> param = client.newParam(3);
        param.put(YunpianClient.MOBILE, mobile);
        param.put(YunpianClient.TPL_ID, tplId);
        param.put(YunpianClient.TPL_VALUE, tplValue);
        Result<SmsSingleSend> result = client.sms().single_send(param);
        log.info("短信发送结果" + result.toString());
        if (result.getCode() == 0) {
            //返回成功结果
            SendMsgWorkResponse msgData = new SendMsgWorkResponse();
            msgData.setCount(result.getData().getCount());
            msgData.setFee(new BigDecimal(result.getData().getFee()).setScale(2, RoundingMode.DOWN));
            return Response.data(msgData);
        } else {
            return Response.failed("发送失败:" + result.getMsg());
        }
    }

    /**
     * 发送短信信息
     *
     * @param mobile 群发模式下多个手机号用逗号分隔
     * @param msg
     * @param type
     * @return single:单发模式;batch:群发模式
     */
    @Override
    public Response sendMsg(String mobile, String msg, String type, String apiKey) {
        YunpianClient client = new YunpianClient(apiKey).init();
        Map<String, String> param = client.newParam(2);
        param.put(YunpianClient.MOBILE, mobile);
        param.put(YunpianClient.TEXT, msg);
        Result result = null;
        int count = 0;
        BigDecimal fee = null;
        switch (type) {
            case "single": {
                result = client.sms().single_send(param);
                log.info("短信发送结果" + result.toString());
                if (result.getCode() == 0) {
                    SmsSingleSend data = (SmsSingleSend) result.getData();
                    count = data.getCount();
                    fee = new BigDecimal(data.getFee()).setScale(2, RoundingMode.DOWN);
                } else {
                    return Response.failed("发送失败:" + result.getMsg());
                }
                break;
            }

            case "batch": {
                result = client.sms().batch_send(param);
                log.info("短信发送结果" + result.toString());
                if (result.getCode() == 0) {
                    SmsBatchSend data = (SmsBatchSend) result.getData();
                    count = data.getTotal_count();
                    fee = new BigDecimal(data.getTotal_fee()).setScale(2, RoundingMode.DOWN);
                } else {
                    return Response.failed("发送失败:" + result.getMsg());
                }
                break;
            }
            default:
                return Response.failed("发送失败:不支持的发送模式");
        }
        //返回成功结果
        SendMsgWorkResponse msgData = new SendMsgWorkResponse();
        msgData.setCount(count);
        msgData.setFee(fee);
        return Response.data(msgData);

    }

    /**
     * 根据模板发送短信信息
     *
     * @param mobile 群发模式下多个手机号用逗号分隔
     * @param tplId
     * @param tplValueMap
     * @param type single:单发模式;batch:群发模式
     * @return
     */
    @Override
    public Response sendTplMsg(String mobile, String tplId, Map<String, String> tplValueMap, String type,
            String apiKey) {
        YunpianClient client = new YunpianClient(apiKey).init();
        String tplValue = getTplValueStr(tplValueMap);
        Map<String, String> param = client.newParam(3);
        param.put(YunpianClient.MOBILE, mobile);
        param.put(YunpianClient.TPL_ID, tplId);
        param.put(YunpianClient.TPL_VALUE, tplValue);
        Result result = null;
        int count = 0;
        BigDecimal fee = null;
        switch (type) {
            case "single": {
                result = client.sms().tpl_single_send(param);
                log.info("短信发送结果" + result.toString());
                if (result.getCode() == 0) {
                    SmsSingleSend data = (SmsSingleSend) result.getData();
                    count = data.getCount();
                    fee = new BigDecimal(data.getFee()).setScale(2, RoundingMode.DOWN);
                } else {
                    return Response.failed("发送失败:" + result.getMsg());
                }
                break;
            }
            case "batch": {
                result = client.sms().tpl_batch_send(param);
                log.info("短信发送结果" + result.toString());
                if (result.getCode() == 0) {
                    SmsBatchSend data = (SmsBatchSend) result.getData();
                    count = data.getTotal_count();
                    fee = new BigDecimal(data.getTotal_fee()).setScale(2, RoundingMode.DOWN);
                } else {
                    return Response.failed("发送失败:" + result.getMsg());
                }
                break;
            }
            default:
                return Response.failed("发送失败:不支持的发送模式");
        }
        //返回成功结果
        SendMsgWorkResponse msgData = new SendMsgWorkResponse();
        msgData.setCount(count);
        msgData.setFee(fee);
        return Response.data(msgData);

    }

    /**
     * 添加模板
     *
     * @param tplContent 模板内容，必须以带符号【】的签名开头
     * @param apiKey 用户唯一标识
     * @return
     */
    @Override
    public Response addTpl(String tplContent, String apiKey) {
        YunpianClient client = new YunpianClient(apiKey).init();
        Map<String, String> param = client.newParam(1);
        param.put(YunpianClient.TPL_CONTENT, tplContent);
        Result result = client.tpl().add(param);
        log.info("添加模板结果" + result.toString());
        if (result.getCode() == 0) {
            //返回成功结果
            return Response.data(result);
        } else {
            return Response.failed("发送失败:" + result.getMsg());
        }
    }

    /**
     * 修改模板
     *
     * @param tplId 模板id
     * @param tplContent 模板内容，必须以带符号【】的签名开头
     * @param apiKey 用户唯一标识
     * @return
     */
    @Override
    public Response updateTpl(String tplId, String tplContent, String apiKey) {
        YunpianClient client = new YunpianClient(apiKey).init();
        Map<String, String> param = client.newParam(1);
        param.put(YunpianClient.TPL_CONTENT, tplContent);
        param.put(YunpianClient.TPL_ID, tplId);
        Result result = client.tpl().update(param);
        log.info("修改模板结果" + result.toString());
        if (result.getCode() == 0) {
            //返回成功结果
            return Response.data(result);
        } else {
            return Response.failed("发送失败:" + result.getMsg());
        }
    }
}
